import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/token'
import { constantRoute } from '@/router/route'
import type { RouteRecordRaw } from 'vue-router'
import type {
  LoginDataType,
  LoginResponseType,
  UserInfoResponseType,
} from '@/api/user/types'
import { ref } from 'vue'
export const useUserStore = defineStore('User', () => {
  //路由信息
  const MenuRoute: RouteRecordRaw[] = constantRoute
  //用户TOKEN
  let token = ref(getToken())
  //用户信息
  const userName = ref<string>('')
  const userAvatar = ref<string>('')
  //用户登录
  const userLogin = async (data: LoginDataType) => {
    //发送登陆请求
    const res: LoginResponseType = await reqLogin(data)
    console.log(res)
    //登陆成功
    if (res.code === 200) {
      //持久化存储TOKEN
      setToken(res.data as string)
      token.value = res.data as string
      return Promise.resolve('success')
    } else {
      return Promise.reject(new Error(res.message))
    }
  }
  //获取用户信息
  const getUserInfo = async () => {
    try {
      const result: UserInfoResponseType = await reqUserInfo()
      console.log(result)
      if (result.code === 200) {
        userName.value = result.data.name
        userAvatar.value = result.data.avatar
        return Promise.resolve('success')
      } else {
        return Promise.reject('TOKEN失效')
      }
    } catch (error) {
      console.error('Get user info failed', error)
    }
  }
  const userLogout = async () => {
    try {
      await reqLogout()
      emptyStore()
      return Promise.resolve('success')
    } catch (error) {
      console.log('@@@@')
      console.log(error)
      return Promise.reject(error)
    }
  }
  const emptyStore = (): void => {
    token.value = ''
    userName.value = ''
    userAvatar.value = ''
    removeToken()
  }

  return {
    token,
    userLogin,
    MenuRoute,
    getUserInfo,
    userName,
    userAvatar,
    userLogout,
    emptyStore,
  }
})
